package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.ExtBusinessApplication;
import com.ruoyi.business.mapper.ExtBusinessApplicationMapper;
import com.ruoyi.business.service.IExtBusinessApplicationService;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.UniqueIdGenerator;
import com.ruoyi.system.api.RemoteDynamicSqlService;
import com.ruoyi.system.api.domain.DynamicSql;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 应用定义Service业务层处理
 *
 * @author ruoyi
 * @date 2024-09-24
 */
@Service
@Slf4j
public class ExtBusinessApplicationServiceImpl implements IExtBusinessApplicationService
{
    @Autowired
    private ExtBusinessApplicationMapper extBusinessApplicationMapper;
    @Autowired
    private RemoteDynamicSqlService remoteDynamicSqlService;
    /**
     * 查询应用定义
     *
     * @param id 应用定义主键
     * @return 应用定义
     */
    @Override
    public ExtBusinessApplication selectExtBusinessApplicationById(Long id)
    {
        return extBusinessApplicationMapper.selectExtBusinessApplicationById(id);
    }

    /**
     * 查询应用定义列表
     *
     * @param extBusinessApplication 应用定义
     * @return 应用定义
     */
    @Override
    public List<ExtBusinessApplication> selectExtBusinessApplicationList(ExtBusinessApplication extBusinessApplication)
    {
        return extBusinessApplicationMapper.selectExtBusinessApplicationList(extBusinessApplication);
    }

    /**
     * 新增应用定义
     *
     * @param extBusinessApplication 应用定义
     * @return 结果
     */
    @Override
    public int insertExtBusinessApplication(ExtBusinessApplication extBusinessApplication)
    {
        extBusinessApplication.setCreateTime(DateUtils.getNowDate());
        //产生命名空间串
        extBusinessApplication.setNameSpace(UniqueIdGenerator.getUniqueId(8));
        //
        int rownum =  extBusinessApplicationMapper.insertExtBusinessApplication(extBusinessApplication);
        //初始化应用相关数据
        initApplicationInfo(extBusinessApplication);
        return rownum;
    }
    /**
     * 初始化应用信息：菜单，权限，角色等
     * @param extBusinessApplication
     */
    private void initApplicationInfo(ExtBusinessApplication extBusinessApplication) {
        String filePath = "/sql/applicationinit.sql";
        try  {
            InputStream inputStream = org.apache.commons.io.FileUtils.class.getResourceAsStream(filePath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            List<String> sqlStatements = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim(); // 去除行首尾的空白字符
                if (line.isEmpty() || line.startsWith("--")) {
                    continue; // 跳过空行和注释
                }
                if (line.endsWith(";")) {
                    //去掉分号
                    sb.append(line).append(" ");
                    int pos = sb.lastIndexOf(";");
                    sb.setLength(pos);
                    //替换租户编码
                    String sql = sb.toString().replace("${enterpriseCode}",extBusinessApplication.getEnterpriseCode());
                    sql = sql.replace("${applicationCode}", extBusinessApplication.getApplicationCode());
                    //替换用户名
                    sql = sql.replace("${userName}", SecurityContextHolder.getUserName());
                    sqlStatements.add(sql);
                    sb.setLength(0); // 清空 StringBuilder
                }else{
                    sb.append(line).append(" ");
                }
            }
            inputStream.close();
            DynamicSql dynamicSql = new DynamicSql();
            for (String sql : sqlStatements) {
                dynamicSql.setSql(sql);
                log.info("执行SQL: {}", sql);
                try {
                    R<Integer> result = remoteDynamicSqlService.doUpdate(dynamicSql);
                    // 处理结果
                } catch (IllegalArgumentException e) {
                    log.error("Feign调用参数类型不匹配: {}", e.getMessage(), e);
                    throw new ServiceException("服务调用参数类型不匹配");
                } catch (Exception e) {
                    log.error("Feign调用异常: {}", e.getMessage(), e);
                    throw new ServiceException("服务调用失败");
                }

            }


        } catch (IOException e) {
            e.printStackTrace();
            log.error("初始化应用信息失败！",e);
            throw new ServiceException("初始化应用信息失败！");
        }
    }

    /**
     * 修改应用定义
     *
     * @param extBusinessApplication 应用定义
     * @return 结果
     */
    @Override
    public int updateExtBusinessApplication(ExtBusinessApplication extBusinessApplication)
    {
        extBusinessApplication.setUpdateTime(DateUtils.getNowDate());
        //如果命名空间串为空，则重新生成
        if(StringUtils.isEmpty(extBusinessApplication.getNameSpace())) {
            extBusinessApplication.setNameSpace(UniqueIdGenerator.getUniqueId(8));
        }
        return extBusinessApplicationMapper.updateExtBusinessApplication(extBusinessApplication);
    }

    /**
     * 批量删除应用定义
     *
     * @param ids 需要删除的应用定义主键
     * @return 结果
     */
    @Override
    public int deleteExtBusinessApplicationByIds(Long[] ids)
    {
        return extBusinessApplicationMapper.deleteExtBusinessApplicationByIds(ids);
    }

    /**
     * 删除应用定义信息
     *
     * @param id 应用定义主键
     * @return 结果
     */
    @Override
    public int deleteExtBusinessApplicationById(Long id)
    {
        return extBusinessApplicationMapper.deleteExtBusinessApplicationById(id);
    }

    /**
     * 查询满足条件条数
     *
     * @param searchMap
     * @return
     */
    @Override
    public int selectCount(Map<String, Object> searchMap) {
        return extBusinessApplicationMapper.selectCount(searchMap);
    }
}
